package com.edu.chapter07.listener;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

public class ChildGestureListener extends GestureDetector.SimpleOnGestureListener {
    private final View targetView;
    private View activeDragView; // 当前拖拽的控件
    private float lastX, lastY;

    public ChildGestureListener(View targetView) {
        this.targetView = targetView;
        activeDragView = targetView;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        lastX = e.getRawX();
        lastY = e.getRawY();
        activeDragView = targetView;
        return true;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
        // 拖拽移动逻辑
        float currentX = e2.getRawX();
        float currentY = e2.getRawY();
        float offsetX = currentX - lastX;
        float offsetY = currentY - lastY;

        targetView.setTranslationX(targetView.getTranslationX() + offsetX);
        targetView.setTranslationY(targetView.getTranslationY() + offsetY);

        lastX = currentX;
        lastY = currentY;
        return true;
    }

    public void insertViewAtPosition() {
        ViewGroup parent = (ViewGroup) targetView.getParent();
        int currentIndex = parent.indexOfChild(targetView);
        int newIndex = findInsertIndex(parent, targetView.getX(), targetView.getY());

        if (newIndex != currentIndex) {
            parent.removeView(targetView);
            parent.addView(targetView, Math.min(newIndex, parent.getChildCount()));
            parent.requestLayout(); // 强制重新布局
        }

        targetView.setTranslationX(0); // 重置位置
        targetView.setTranslationY(0);
    }

    // 根据拖拽控件的中心坐标，找到最近的插入点（欧氏距离最小）
    private int findInsertIndex(ViewGroup parent, float centerX, float centerY) {
        int newIndex = -1;
        float minDistance = Float.MAX_VALUE;

        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            float childCenterX = child.getLeft() + child.getWidth() / 2f;
            float childCenterY = child.getTop() + child.getHeight() / 2f;

            float distance = (float) Math.sqrt(
                    Math.pow(centerX - childCenterX, 2) +
                            Math.pow(centerY - childCenterY, 2)
            );

            if (distance < minDistance) {
                minDistance = distance;
                newIndex = i;
            }
        }
        return newIndex;
    }


}
